package store.lunangangster.nodeflow.parser.el.operator;

import static store.lunangangster.nodeflow.enums.FlowType.FLOW_THEN;

import cn.hutool.core.collection.CollUtil;
import com.ql.util.express.Operator;
import store.lunangangster.nodeflow.builder.FlowBuilder;
import store.lunangangster.nodeflow.exception.RuleSourceParseException;
import store.lunangangster.nodeflow.parser.el.OperatorHelper;
import store.lunangangster.nodeflow.rt.element.Executable;
import store.lunangangster.nodeflow.rt.element.flow.IfFlow;
import store.lunangangster.nodeflow.util.Converter;

/**
 * 用于扩展IfFlow的ELSE操作符
 *
 * @author cwk
 * @version 1.0
 */
public class ElseOperator extends Operator {

  @Override
  public Object executeInner(Object[] list) {
    IfFlow ifFlow = Converter.convert(list[0], IfFlow.class);
    if (ifFlow.isElse()) {
      throw new RuleSourceParseException("Incompatible executable for ElseFlow: former IfFlow already has falseBranch, cannot use ELSEIF() or ELSE() again");
    }
    if (list.length != 2) {
      throw new RuleSourceParseException("Incompatible executable for ElseFlow: should be like ELSE(Flow)");
    }
    // never be null
    OperatorHelper.findFalseBranchLeaf(ifFlow).setFalseBranch(FlowBuilder.buildELFLow(FLOW_THEN, CollUtil.toList((Executable) list[1])));
    ifFlow.setIsElse(true);
    return ifFlow;
  }
}
